import os
import wx
from cef_utils import *
from cefpython3 import cefpython as cef

from ui_out import DFrame
# Globals
g_count_windows = 0


class MainFrame(DFrame):

    _browser = None
    panel_browser = None

    def __init__(self, width=1280, height=760, url="http://www.smzdm.com"):
        self._browser = None
        global g_count_windows
        g_count_windows += 1

        DFrame.__init__(self, parent=None, id=wx.ID_ANY,
                           size=(width / 2, height / 2))
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.init_browser(width, height)
        self.init_filetree()
        self.Show()

    def init_filetree(self):
        tree = self.tree_filelist
        

    def init_browser(self, width, height):
        # Set wx.WANTS_CHARS style for the keyboard to work.
        # This style also needs to be set for all parent controls.
        
        self.panel_browser.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.panel_browser.Bind(wx.EVT_SIZE, self.OnSize)
        # self._panel_brawser.Scale(0.5)
        if MAC:
            # Make the content view for the window have a layer.
            # This will make all sub-views have layers. This is
            # necessary to ensure correct layer ordering of all
            # child views and theirz layers. This fixes Window
            # glitchiness during initial loading on Mac (Issue #371).
            NSApp.windows()[0].contentView().setWantsLayer_(True)

        window_info = cef.WindowInfo()
        (width, height) = self.panel_browser.GetClientSize().Get()
        assert self.panel_browser.GetHandle(), "Window handle not available"
        window_info.SetAsChild(self.panel_browser.GetHandle(),
                               [0, 0, width, height])

        browser = cef.CreateBrowserSync(window_info,
                                        url="http://www.smzdm.com/")
        if not browser.HasDevTools():
            print("has devtools")
            browser.ShowDevTools()
        browser.SetAutoResizeEnabled(False, [width, height], [width, height])
        browser.SetClientHandler(FocusHandler())
        self._browser = browser

    def OnSetFocus(self, _):
        if not self._browser:
            return
        self._browser.SetFocus(True)

    def OnSize(self, _):
        if not self._browser:
            return
        self._browser.NotifyMoveOrResizeStarted()

    def OnClose(self, event):
        print("[wxpython.py] OnClose called")
        if not self._browser:
            # May already be closing, may be called multiple times on Mac
            return
            
        self._browser.CloseBrowser()
        self.Destroy()
        self._browser = None
        global g_count_windows
        g_count_windows -= 1
        if g_count_windows == 0:
            cef.Shutdown()
            wx.GetApp().ExitMainLoop()
            # Call _exit otherwise app exits with code 255 (Issue #162).
            # noinspection PyProtectedMember
            os._exit(0)


class FocusHandler(object):
    def OnGotFocus(self, browser, **_):
        # Temporary fix for focus issues on Linux (Issue #284).
        if LINUX:
            print("[wxpython.py] FocusHandler.OnGotFocus:"
                  " keyboard focus fix (Issue #284)")
            browser.SetFocus(True)
